import { TreeNodeDataModel } from '@/components/Tree/types'

export const merge = function (target: TreeNodeDataModel, source: TreeNodeDataModel) {
  if (target.id !== source.id) return source
  // 判断新的对象是否存在chilren 不存在不做处理
  if (source.children) {
    // 判断目标对象是否在chidren不存在则添加
    if (!target.children) {
      target.children = source.children
    } else {
      // 循环新对象的chidren
      for (let i = 0; i < source.children.length; i++) {
        let isExist = false
        let data: TreeNodeDataModel = {} as any
        // 新对象的chilren和目标对象的chilren对比找出相同的节点
        for (let j = 0; j < target.children.length; j++) {
          if (target.children[j].id === source.children[i].id) {
            isExist = true
            data = target.children[j]
          }
        }
        // 存在相同的节点  继续对比
        if (isExist) {
          merge(data, source.children[i])
        } else { // 反之像目标对象中添加
          data.children?.push(source.children[i])
        }
      }
    }
  }
}

// 查找插入节点的key
export const findNodeKey = function (target: TreeNodeDataModel, source: TreeNodeDataModel) {
  let id = ''
  let children: TreeNodeDataModel[] = []
  if (target.children && source.children) {
    if (!target.children.length || target.children[0].hasOwnProperty('_state_')) {
      id = target.id
      children = source.children
    } else {
      for (let i = 0; i < source.children.length; i++) {
        if (!source.children[i].children?.length) continue
        for (let j = 0; j < target.children.length; j++) {
          if (target.children[i].id === source.children[i].id) {
            const value = findNodeKey(target.children[i], source.children[i])
            id = value.id
            children = value.children
            i = source.children.length
            break
          }
        }
      }
    }
  }
  return { id, children }
}
